/*
 * Copyright 2017 ~ 2025 the original author or authors. <wanglsir@gmail.com, 983708408@qq.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.wl4g.sample.callgo.utils;

import java.nio.charset.Charset;

/**
 * {@link CTypeUtils}
 * 
 * @author Wangl.sir &lt;wanglsir@gmail.com, 983708408@qq.com&gt;
 * @version 2020年6月21日 v1.0.0
 * @see
 */
public abstract class CTypeUtils {

	/**
	 * 在 C 中的 char 数组是以一个 NULL 字符作为结束中止标识， 使用 jdk 中的 toBytes() 并不会在byte
	 * 数组后加结束符，导致读取参数数组越界，强制结束。所以在getBytes()转为 byte 数组后我们需要 人为在结尾加上0来作为中止字符，当然
	 * Matthias Bläsing 也给出了 JNA 解决方法 ， Native#toByteArray 做了部分重写。
	 * 
	 * @param s
	 *            The string
	 * @return A NUL-terminated byte buffer equivalent to the given String,
	 *         using the given encoding.
	 * @see #getBytes(String, String)
	 * @see https://yq.aliyun.com/articles/663961
	 */
	public static byte[] toByteArray(String s, String encoding) {
		byte[] bytes = s.getBytes(Charset.forName(encoding));
		byte[] buf = new byte[bytes.length + 1];
		System.arraycopy(bytes, 0, buf, 0, bytes.length);
		return buf;
	}

}
